<template>
	<view class="page">
		<!-- New Filter/Sort Row -->
		

		<view class="search-box">
			<u-search placeholder="姓名或手机号" v-model="keyword" shape="square" :clearabled="true" :show-action="true"
				action-text="搜索" :animation="true" :action-style="actionstyle" @custom="custom" @search="custom"
				:input-style="inputStyle" :height="80">
			</u-search>
		</view>
		<view class="filter-sort-row">
			<view class="filter-sort-item" @click="openSortPicker">
				<text>{{ currentSortText }}</text>
				<image src="/static/img/ic_next_double_down.png" mode="widthFix" style="width: 24rpx; height: 24rpx; margin-left: 3rpx;"></image>
			</view>
			<view class="filter-sort-item" @click="openFilterPicker">
				<text>{{ currentFilterText }}{{poNum}}人</text>
				<image src="/static/img/ic_next_double_down.png" mode="widthFix" style="width: 24rpx; height: 24rpx; margin-left: 3rpx;"></image>
			</view>
		</view>
		<view class="" style="background-color: #fff;margin-bottom: 5px;">
			<view class="agent_a">
				<view class="agent_ab">
					<view class="photo">
						<image :src="user.imgUrl?user.imgUrl:'/static/img/index/photo.png'"
							style="width:61px;height:61px;border-radius: 50%;"></image>
					
					</view>
					<view style="padding:0 40rpx;">
						<view style="display: flex;align-items: center;">
							<text class="name">{{user.userName}}</text>
							<view class="vip_icon">
								<view>
									<image
										:src="user.type=='1'?'/static/img/index/vip_icon.png' : '/static/img/index/ic_member_normal.png'"
										style="width:24rpx;height:22rpx;"></image>
									<text :class="user.type=='1'?'vip_active':''"
										style="padding-left:4rpx;">{{user.type=='1'?profitConfig.levelName:'会员'}}</text>
								</view>
							</view>
						</view>
						<view style="margin-top: 5px;">(客户经理)</view>
					</view>
				</view>
			
			</view>
			<view hover-class="none" class="agent_ab agent_b " @click="navigatorDataZJ(user,info)">
				<view class="agent_left agent_amt">
					<view class="agent_h">本月总交易额(万元)</view>
					<view>{{(number.parsePrice(info.myTrxAmt)/10000).toFixed(2)}}</view>
				</view>
				<view class="agent_ab agent_to" >
					<view class="agent_left" style="width: 50%;">
						<view class="agent_h">商户数</view>
						<view>{{info.jihuoNum}}</view>
					</view>
					<view style="position: relative;width: 50%;">
						<view class="agent_h">服务商数</view>
						<view class="fws">{{info.userNum}}&nbsp;<view class="fgx">|</view>&nbsp;{{info.userNumTd}}</view>
						<image src="/static/img/ic_next_double.png" mode="widthFix" style="width: 10px; position: absolute; right: 0; top: 50%;"></image>
					</view>
				</view>
			</view>
		</view>
		<view class="redeem-list">
			<view class="redeem-list-list">
				<mescroll-uni ref="mescroll" :fixed="false" @init="mescrollInit" :height="height" :down="downOption"
					@down="downCallback" :up="upOption" @up="upCallback" @emptyclick="emptyClick">
					<view class="Goos-List">
						<view style="background-color: white; margin-bottom: 5px;" v-for="(item,index) in records" :key="index">
							<view class="agent_a">
								<view class="agent_ab">
									<view class="photo">
										<image :src="item.imgUrl?item.imgUrl:'/static/img/index/photo.png'"
											style="width:61px;height:61px;border-radius: 50%;"></image>
										
									</view>
									<view style="padding:0 40rpx; display: flex;align-items: center;" >
										<text>{{item.userName}}</text>
									<view class="vip_icon">
										<view>
											<image
												:src="item.type=='1'?'/static/img/index/vip_icon.png' : '/static/img/index/ic_member_normal.png'"
												style="width:24rpx;height:22rpx;"></image>
											<!-- <text :class="item.type=='1'?'vip_active':''"
												style="padding-left:4rpx;">{{item.type=='1'?item.profitName:'会员'}}</text> -->
												<text :class="item.type=='1'?'vip_active':''"
													style="padding-left:4rpx;">{{item.type=='1'?item.grade:'会员'}}</text>
												
										</view>
									</view>
									</view>
								</view>
								<view class="agent_tel" @click.stop="playCall(item)">
									<image src="/static/img/index/ic_phone_white.png" mode=""></image>
								</view>
								<!-- 实名状态标签 -->
								<view class="sm-tag" v-if="item.sm === '0'" :class="item.sm === '1' ? 'sm-tag-verified' : 'sm-tag-unverified'">
									{{item.sm === '1' ? '已实名' : '未实名'}}
								</view>
							</view>
							<view hover-class="none" class="agent_ab agent_b" @click.stop="navigatorData(item)">
								<view class="agent_left agent_amt">
									<view class="agent_h">本月总交易额(万元)</view>
									<view>{{(number.parsePrice(item.trxAmt)/10000).toFixed(2)}}</view>
									
								</view>
								<view class="agent_ab agent_to">
									<view class="agent_left" style="width: 50%;">
										<view class="agent_h">商户数</view>
										<view>{{item.jihuo}}</view>
									</view>
									<view style="position: relative;width: 50%;">
										<view class="agent_h">服务商数</view>
										<view class="fws">{{item.userNum}}&nbsp;<view class="fgx">|</view>&nbsp;{{item.userNumTd}}</view>
										<image src="/static/img/ic_next_double.png" mode="widthFix" style="width: 10px; position: absolute; right: 0; top: 50%;"></image>
									</view>
								</view>
							</view>
						</view>

					</view>
				</mescroll-uni>
			</view>
		</view>

		<!-- Sort Picker -->
		<u-popup v-model="showSortPicker" mode="bottom">
			<view class="popup-content">
				<view class="popup-header">
					<text @click="showSortPicker = false">取消</text>
					<text @click="confirmSortPicker">确定</text>
				</view>
				<view class="popup-body">
					<picker-view 
						:value="sortPickerValue" 
						@change="onSortPickerChange" 
						style="width: 100%; height: 240px;"
						:indicator-style="indicatorStyle">
						<picker-view-column>
							<view class="picker-item" v-for="(item, index) in sortList" :key="index">{{item.label}}</view>
						</picker-view-column>
					</picker-view>
				</view>
			</view>
		</u-popup>
		<!-- Filter Picker -->
		<u-popup v-model="showFilterPicker" mode="bottom">
			<view class="popup-content">
				<view class="popup-header">
					<text @click="showFilterPicker = false">取消</text>
					<text @click="confirmFilterPicker">确定</text>
				</view>
				<view class="popup-body">
					<picker-view 
						:value="filterPickerValue" 
						@change="onFilterPickerChange" 
						style="width: 100%; height: 240px;"
						:indicator-style="indicatorStyle">
						<picker-view-column>
							<view class="picker-item" v-for="(item, index) in filterList" :key="index">{{item.label}}</view>
						</picker-view-column>
					</picker-view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import number from "../../utils/number.js";
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
	const api = require('../../config/api');
	const util = require('../../utils/util');
	export default {
		mixins: [MescrollMixin], // 使用mixin
		data() {
			return {
				poNum: 0,
				number: number, //声明number属性并赋值为引入的number模块
				user: {},
				profitConfig: {},
				info: {},
				downOption: {
					auto: false //  false 不自动加载 (mixin已处理第一个tab触发downCallback) true
				},
				upOption: {
					auto: false, // 不自动加载
					noMoreSize: 4,
					textLoading: '加载中 ...', // 加载中的提示文本
					textNoMore: '暂无更多', // 没有更多数据的提示文本
					empty: {
						tip: '暂无相关数据', // 提示
					},
				},
				records: [],
				actionstyle:{
					width: '80rpx',
					fontSize: '28rpx',
					color: '#000000'
				},
				inputStyle: {
					padding: '0 20rpx',
					fontSize: '28rpx'
				},
				keyword:'',
				sx: '0', // 默认排序
				smrz: '-1', // 默认全部（实名认证）
				showSortPicker: false,
				showFilterPicker: false,
				currentSortText: '默认排序',
				currentFilterText: '全部',
				height: '100%', // 添加height属性
				// 选择器样式
				indicatorStyle: 'height: 44px; border-top: 1px solid #eee; border-bottom: 1px solid #eee;',
				// 重构选择器数据结构，使用平铺数组，便于管理
				sortList: [
					{ label: '默认排序', value: '0' },
					{ label: '等级排行', value: '1' },
					{ label: '用户激活排行', value: '2' },
					{ label: '本月交易额排行', value: '3' },
					{ label: '本月用户激活排行', value: '4' }
				],
				filterList: [
					{ label: '全部', value: '-1' },
					{ label: '已实名', value: '1' },
					{ label: '未实名', value: '0' }
				],
				sortPickerValue: [0], // 排序选择器当前值
				filterPickerValue: [0], // 筛选选择器当前值
				tempSortIndex: 0, // 临时存储排序索引
				tempFilterIndex: 0, // 临时存储筛选索引
				// 保留原结构兼容现有代码
				sortOptions: [[]],
				filterOptions: [[]],
			}
		},
		onLoad() {
			// 初始化选择项
			this.sortOptions[0] = this.sortList;
			this.filterOptions[0] = this.filterList;
			
			this.getUserInfo();
			// 初始化选择器的值与显示文本匹配
			this.initPickerValues();
		},
		onShow() {
			// 移除可能导致错误的代码
		},
		methods: {
			// mescroll初始化的回调,可获取到mescroll对象
			mescrollInit(mescroll) {
				this.mescroll = mescroll;
				console.log("mescroll初始化完成");
			},
			// 初始化选择器的值与显示文本匹配
			initPickerValues() {
				// 排序选择器初始化
				const sortIndex = this.getIndexByValue(this.sortList, this.sx);
				this.sortPickerValue = [sortIndex];
				this.currentSortText = this.sortList[sortIndex].label;
				
				// 筛选选择器初始化
				const filterIndex = this.getIndexByValue(this.filterList, this.smrz);
				this.filterPickerValue = [filterIndex];
				this.currentFilterText = this.filterList[filterIndex].label;
				
				// 打印初始状态
				console.log("初始排序:", this.sx, this.currentSortText, "索引:", sortIndex);
				console.log("初始筛选:", this.smrz, this.currentFilterText, "索引:", filterIndex);
			},
			// 根据value查找选项索引 - 优化版
			getIndexByValue(list, value) {
				if (!list || !Array.isArray(list)) {
					return 0;
				}
				
				for (let i = 0; i < list.length; i++) {
					if (list[i] && list[i].value === value) {
						return i;
					}
				}
				return 0; // 默认返回第一项
			},
			custom(){
				this.keyword = this.keyword.trim();
				this.downCallback();
			},
			clearKeywordAndRefresh() {
				this.keyword = ''; // 清空搜索框
				
				// 显示加载中提示，不使用mask以免阻止滚动
				uni.showLoading({
					title: '加载中...',
					mask: false
				});
				
				// 检查mescroll对象是否存在
				if (this.mescroll) {
					this.mescroll.resetUpScroll();
				} else {
					this.downCallback(); // 备用方案，如果mescroll不存在，直接调用downCallback
				}
				console.log("当前排序:", this.sx, this.currentSortText);
				console.log("当前筛选:", this.smrz, this.currentFilterText);
			},
			openSortPicker() {
				// 打开前确保当前索引与选中值匹配
				const index = this.getIndexByValue(this.sortList, this.sx);
				this.sortPickerValue = [index];
				this.tempSortIndex = index;
				console.log("打开排序选择器，当前值:", this.sx, "对应索引:", index);
				this.showSortPicker = true;
			},
			onSortPickerChange(e) {
				// 安全检查
				if (!e || !e.detail || !Array.isArray(e.detail.value)) {
					return;
				}
				
				const index = e.detail.value[0] || 0;
				this.tempSortIndex = index;
				
				// 输出当前选择的项
				if (this.sortList[index]) {
					console.log("排序切换为:", this.sortList[index].label, "值:", this.sortList[index].value);
				}
			},
			confirmSortPicker() {
				const index = typeof this.tempSortIndex === 'number' ? this.tempSortIndex : 0;
				
				// 确保索引在有效范围内
				const validIndex = Math.max(0, Math.min(index, this.sortList.length - 1));
				const selectedItem = this.sortList[validIndex];
				
				if (selectedItem) {
					// 更新值和文本
					this.sx = selectedItem.value;
					this.currentSortText = selectedItem.label;
					// 更新选择器当前值
					this.sortPickerValue = [validIndex];
					
					console.log("确认排序:", this.currentSortText, "值:", this.sx, "索引:", validIndex);
				} else {
					console.error("排序选择出错：无法获取选中项");
				}
				
				this.showSortPicker = false;
				this.clearKeywordAndRefresh();
			},
			openFilterPicker() {
				// 打开前确保当前索引与选中值匹配
				const index = this.getIndexByValue(this.filterList, this.smrz);
				this.filterPickerValue = [index];
				this.tempFilterIndex = index;
				console.log("打开筛选选择器，当前值:", this.smrz, "对应索引:", index);
				this.showFilterPicker = true;
			},
			onFilterPickerChange(e) {
				// 安全检查
				if (!e || !e.detail || !Array.isArray(e.detail.value)) {
					return;
				}
				
				const index = e.detail.value[0] || 0;
				this.tempFilterIndex = index;
				
				// 输出当前选择的项
				if (this.filterList[index]) {
					console.log("筛选切换为:", this.filterList[index].label, "值:", this.filterList[index].value);
				}
			},
			confirmFilterPicker() {
				const index = typeof this.tempFilterIndex === 'number' ? this.tempFilterIndex : 0;
				
				// 确保索引在有效范围内
				const validIndex = Math.max(0, Math.min(index, this.filterList.length - 1));
				const selectedItem = this.filterList[validIndex];
				
				if (selectedItem) {
					// 更新值和文本
					this.smrz = selectedItem.value;
					this.currentFilterText = selectedItem.label;
					// 更新选择器当前值
					this.filterPickerValue = [validIndex];
					
					console.log("确认筛选:", this.currentFilterText, "值:", this.smrz, "索引:", validIndex);
				} else {
					console.error("筛选选择出错：无法获取选中项");
				}
				
				this.showFilterPicker = false;
				this.clearKeywordAndRefresh();
			},
			navigateAgent(){
				console.log('触发跳转');
			},
			playCall(item){
				
				// console.log('拨打电话');
				uni.makePhoneCall({
					phoneNumber: item.phone //仅为示例
				});
			},
			navigatorData(item){
				
				uni.setStorageSync('agentInfo',item)
				uni.navigateTo({
					url:'/pages/myAgent/agentData'
				})
			},
			navigatorDataZJ(item,info){
				let items = item
				items.userNum = info.userNum
				uni.setStorageSync('agentInfo',items)
				uni.setStorageSync('agentInfoinfo',info)
				uni.navigateTo({
					url:'/pages/myAgent/agentData'
				})
			},
			async getUserInfo() {
				const res = await util.request(
					api.getUserInfoUrl, {},
					'POST'
				);
				console.log(res);
				if (res.code !== 0) {
					uni.showToast({
						title: res.msg,
						icon: "none"
					})

				} else {
					this.user = res.data.user,
						this.profitConfig = res.data.profitConfig
					// this.gemyAgent()
					this.downCallback();
				}
			},
			async gemyAgent() {
				const res = await util.request(
					api.myAgentUrl, {
						"limit": 10,
						"merName": this.keyword,
						"page": 1
					},
					'POST'
				);
				console.log(res);
				if (res.code !== 0) {
					uni.showToast({
						title: res.msg,
						icon: "none"
					})

				} else {
					this.info = res.data
				}
			},
			/*下拉刷新的回调 */
			downCallback() {
				// 这里加载你想下拉刷新的数据, 比如刷新轮播数据
				// loadSwiper();
				// 下拉刷新的回调,默认重置上拉加载列表为第一页 (自动执行 page.num=1, 再触发upCallback方法 )
				// 注意：关键字 `this.keyword` 在此处不清空，允许带关键字下拉刷新
				this.mescroll.resetUpScroll()
			},
			/*上拉加载的回调: 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10 */
			upCallback(page) {
				//联网加载数据
				// this.mescroll.endErr();
				// let keyword = this.tabs[this.i].dictValue
				let pageNum = page.num; // 页码, 默认从1开始
				let pageSize = page.size; // 页长, 默认每页10条
				
				// 组装请求参数
				const requestParams = {
					page: pageNum,
					merName: this.keyword,
					limit: pageSize,
					sx: this.sx, // 排序参数
					smrz: this.smrz // 实名认证筛选参数
				};
				
				// 打印请求参数
				console.log('请求参数:', JSON.stringify(requestParams));
				
				const res = util.request(
					api.myAgentUrl, 
					requestParams,
					'POST'
				).then(res => {
					// 请求完成后隐藏加载提示
					uni.hideLoading();
					
					if (res.code !== 0) {
						uni.showToast({
							title: res.msg,
							icon: "none"
						})
					
					} else {
						this.info = res.data
						
						console.log(res);
						this.poNum=res.data.page.total;
						//联网成功的回调,隐藏下拉刷新和上拉加载的状态;
						let totalPage = res.data.page.pages;
						this.mescroll.endByPage(res.data.page.records.length, totalPage); //必传参数(当前页的数据个数, 总页数)
						// this.mescroll.endSuccess(res.data.page.records);
						//设置列表数据
						if (page.num == 1) this.records = []; //如果是第一页需手动制空列表
						// this.records = this.records.concat(res.data.page.records); //追加新数据
						let listArry = [];
						let list = res.data.page.records;
						for (let i = 0; i < list.length; i++) {
							listArry.push(Object.assign(list[i], JSON.parse(list[i].remarks)));
						}
						this.records = this.records.concat(listArry)
					}
					
				}).catch(() => {
					// 请求出错时也需要隐藏加载提示
					uni.hideLoading();
					
					//联网失败, 结束加载
					this.mescroll.endErr();
				})
			},
			emptyClick() {
				uni.showToast({
					title: '点击了按钮,具体逻辑自行实现'
				})
			}


		}
	}
</script>

<style>
	page {
		height: 100%;
		background-color: #F4F5F7;
	}

	.mescroll-upwarp {
		min-height: 0rpx !important;
	}
	
	/* 确保滚动区域可以正常工作 */
	.mescroll-uni {
		position: relative !important;
		height: 100% !important;
		max-height: 100% !important;
		overflow-y: auto !important;
	}
</style>
<style lang="scss" scoped>
	.page {
		display: flex;
		flex-direction: column;
		height: 100%;
		overflow: hidden;
	}

	/* pages/agent/myAgent/myAgent.wxss */

	.nav {
		background-color: transparent !important;
	}

	.nav_title {
		color: white !important;
	}

	.van-nav-bar__left {
		color: white !important;
		font-size: 36px;
	}

	.van-hairline--bottom:after {
		border-bottom-width: 0 !important;
	}

	.me-weui {
		background-color: white;
		border-bottom: 1px solid #F9F9F9;
	}

	.head {
		display: flex;
		align-items: center;
		padding: 50rpx 0 150rpx 32rpx;
		background-color: #6A9FFB;

	}

	.photo {
		position: relative;
		display: flex;
	}

	.photo image {
		display: block;
		border-radius: 50%;
		overflow: hidden;
	}

	.vip_icon {
		margin-left: 8px;
		// position: absolute;
		left: 0;
		bottom: -4rpx;
		right: 0;
		z-index: 5;
		display: flex;
		justify-content: center;
	}

	.vip_icon>view {
		display: flex;
		justify-content: center;
		align-items: center;
		background: white;
		border-radius: 40rpx;
		font-size: 20rpx;
		color: #969799;
		width: 84rpx;
	}

	.no_vip {
		width: 100rpx !important;
	}

	.vip_active {
		color: #33D719;
	}

	.user {
		padding: 0 40rpx;
		color: white;
	}

	.name {
		font-size: 36rpx;
		font-weight: 600;
	}

	.agent_data {
		position: relative;
		// height: 100px;
		height: 50px;
	}

	.agent_center {
		position: absolute;
		left: 10px;
		right: 10px;
		bottom: 30rpx;
		background-color: white;
		border-radius: 20rpx;
		padding: 0 32rpx;
		box-shadow: 0px 1px 2px 3px rgba(0, 0, 0, 0.05);
	}

	.agent_list {
		display: flex;
		padding: 20rpx;
	}

	.agent_list>view {
		width: 50%;
		text-align: center;
		font-size: 28rpx;
	}

	.agent_list>view:first-child {
		border-right: 1rpx solid #f5f5f5;
	}

	.agent_num {
		padding-bottom: 10rpx;
	}

	.agent_active {
		color: #F2A761;
	}

	.agent_show {
		color: #48D33D;
	}

	.agent_a {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 64rpx 20rpx 32rpx;
		border-bottom: 1rpx solid #f5f5f5;
		position: relative; /* 添加相对定位，使标签可以绝对定位 */
	}

	.agent_ab {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.agent_amt{
		width: 40%;

	}
	.agent_to{
		width: 60%;

	}
	.agent_tel {
		// background-color: #DA2744;
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		overflow: hidden;
		display: flex;
		justify-content: center;
		align-items: center;
		image{
			width: 100%;
			height: 100%;
		}
	}

	.agent_b {
		padding: 10rpx 32rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.agent_b>view {
		//width: 50%;
		text-align: center;
		font-size: 26rpx;
	}

	.agent_left {
		border-right: 1rpx solid #f5f5f5;
	}

	.agent_bc>view {
		width: 50%;
	}

	.agent_h {
		color: #B0B0B0;
	}

	.bottom {
		display: flex;
		justify-content: center;
		padding: 40rpx 0;
	}

	.van-divider {
		border: none !important;

	}

	.redeem-list {
		flex: 1;
		width: 100%;
		height: 100%;
		overflow: hidden;
		position: relative;
	}

	.redeem-list-list {
		margin-top: 5px;
		width: 100%;
		height: 100%;
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
	}
	.search-box{
		background-color: #fff;
		padding: 12px 15px;
	}

	.filter-sort-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0rpx 32rpx 20rpx 32rpx;
		background-color: #fff;
		border-bottom: 1rpx solid #eee; // 使用 #eee 作为边框颜色，更柔和
		font-size: 28rpx;
		color: #333;
	}

	.filter-sort-item {
		display: flex;
		align-items: center;
		padding: 10rpx; // 增加点击区域
		text {
			margin-right: 8rpx;
		}
	}

	.popup-content {
		background-color: #fff;
		padding: 0 0 40rpx 0;
	}
	
	.popup-header {
		display: flex;
		justify-content: space-between;
		padding: 30rpx;
		font-size: 30rpx;
		border-bottom: 1rpx solid #eee;
	}
	
	.popup-header text:first-child {
		color: #909399;
	}
	
	.popup-header text:last-child {
		color: #3c9cff;
	}
	
	.popup-body {
		padding: 20rpx 0;
	}
	
	.picker-item {
		height: 44px;
		line-height: 44px;
		text-align: center;
		font-size: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.sm-tag {
		position: absolute;
		top: 0;
		right: 0;
		padding: 2px 8px;
		font-size: 22rpx;
		border-radius: 0 0 0 8px;
		color: #fff;
	}
	
	.sm-tag-verified {
		background-color: #19be6b;
	}
	
	.sm-tag-unverified {
		background-color: #c8c8c8;
	}
	.fgx{
		color: #ababab;
		margin: 0rpx 5rpx;
		
	}
	.fws{
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>